package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.heima.admin.utils.common.DateUtils;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.HotArticleService;
import com.heima.common.constants.article.ArticleConstants;
import com.heima.common.excpetion.CustException;
import com.heima.feign.admin.AdminFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.app.ArticleVisitStreamMess;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 热点文章计算
 */
@Service("HotArticleService")
@Transactional(readOnly = true)
public class HotArticleServiceImpl implements HotArticleService {
    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    AdminFeign adminFeign;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 计算热点文章
     */
    @Override
    public void computeHotArticle() {
        // 查询五天的文章数据
        String day = LocalDateTime.now().minusDays(5).format(DateTimeFormatter.ofPattern("yyyy-MM-dd 00:00:00"));
        List<ApArticle> apArticles = apArticleMapper.selectArticleByDate(day);

        //计算文章的分值
        List<HotArticleVo> hotArticleVoList = computeArticleScore(apArticles);
        //缓存每个频道的30条热点文章
        cacheTagToRedis(hotArticleVoList);
    }

    /**
     * 将每个频道的30条热点文章缓存到
     *
     * @param hotArticleVoList 带有分值的集合
     */
    private void cacheTagToRedis(List<HotArticleVo> hotArticleVoList) {
        //查询所有频道信息
        ResponseResult<List<AdChannel>> listResponseResult = adminFeign.selectChannels();

        if (listResponseResult.getCode() == 0) {
            List<AdChannel> channelList = listResponseResult.getData();
            for (AdChannel adChannel : channelList) {
                //取出当前遍历的频道文章
                List<HotArticleVo> hotArticleVos = hotArticleVoList.stream()
                        .filter(hotArticleVo -> hotArticleVo.getChannelId().equals(adChannel.getId()))
                        .collect(Collectors.toList());
                //向redis存入当前频道文章数据
                sortAndCache(hotArticleVos, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + adChannel.getId());
            }
        }
        // 缓存推荐频道的热点文章
        sortAndCache(hotArticleVoList, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG);

    }

    /**
     * 缓存热点文章
     *
     * @param hotArticleVos 带分值的文章集合
     * @param cacheKey      存入的集合名称
     */
    private void sortAndCache(List<HotArticleVo> hotArticleVos, String cacheKey) {
        hotArticleVos = hotArticleVos.stream()
                .sorted(Comparator.comparing(HotArticleVo::getScore).reversed()) // 对文章按照分值进行降序排序
                .limit(30) // 截取前三十条
                .collect(Collectors.toList());

        redisTemplate.opsForValue().set(cacheKey, JSON.toJSONString(hotArticleVos));

    }

    /**
     * 将文章集合转换为带有分值的集合
     *
     * @param apArticles 文章列表
     * @return 带有文章分值的集合
     */
    private List<HotArticleVo> computeArticleScore(List<ApArticle> apArticles) {
        return apArticles.stream().map(apArticle -> {
            HotArticleVo hotArticleVo = new HotArticleVo();
            BeanUtils.copyProperties(apArticle, hotArticleVo);
            // 进行文章分值计算
            Long score = computeScore(apArticle);
            hotArticleVo.setScore(score);
            return hotArticleVo;
        }).collect(Collectors.toList());
    }

    /**
     * 计算单个文章的分值
     *
     * @param apArticle 文章对象
     * @return 计算出的分值
     */
    private Long computeScore(ApArticle apArticle) {
        long score = 0L;

        // 阅读 1
        if (apArticle.getViews() != null) {
            score += apArticle.getViews() * ArticleConstants.HOT_ARTICLE_VIEW_WEIGHT;
        }
        // 点赞 3
        if (apArticle.getLikes() != null) {
            score += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        // 评论 5
        if (apArticle.getComment() != null) {
            score += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        // 收藏 8
        if (apArticle.getCollection() != null) {
            score += apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }
        return score;
    }

    /**
     * 重新计算文章分值
     *
     * @param mess
     */
    @Override
    public void updateApArticle(ArticleVisitStreamMess mess) {
        //1 查询文章
        ApArticle apArticle = apArticleMapper.selectById(mess.getArticleId());
        if (apArticle == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //2 修改文章的行为数据（阅读1、点赞3、评论5、收藏8）
        if (mess.getView() != 0) {
            int view = (int) (apArticle.getViews() == null ? mess.getView() : mess.getView() + apArticle.getViews());
            apArticle.setViews(view);
        }
        if (mess.getLike() != 0) {
            int like = (int) (apArticle.getLikes() == null ? mess.getLike() : mess.getLike() + apArticle.getLikes());
            apArticle.setLikes(like);
        }
        if (mess.getComment() != 0) {
            int comment = (int) (apArticle.getComment() == null ? mess.getComment() : mess.getComment() + apArticle.getComment());
            apArticle.setComment(comment);
        }
        if (mess.getCollect() != 0) {
            int collection = (int) (apArticle.getCollection() == null ? mess.getCollect() : mess.getCollect() + apArticle.getCollection());
            apArticle.setCollection(collection);
        }
        if (mess.getUnlike() != 0) {
            long unlike = (apArticle.getUnlike() == null ? mess.getUnlike() : mess.getUnlike() + apArticle.getUnlike());
            apArticle.setUnlike(unlike);
        }
        if (mess.getFollow() != 0) {
            long follow = (apArticle.getFollow() == null ? mess.getFollow() : mess.getFollow() + apArticle.getFollow());
            apArticle.setFollow(follow);
        }

        mongoTemplate.save(apArticle);
//        apArticleMapper.updateById(apArticle);

        //3 计算文章分值
        long score = computeScore(apArticle);
        // 如果是今天发布的文章，热度*3
        // TODO 如果是六小时内发表的文章权重*3
        String publishStr = DateUtils.dateToString(apArticle.getPublishTime());
        String nowStr = DateUtils.dateToString(new Date());
        if (publishStr.equals(nowStr)){
            score = score*3;  //当天热点数据 *3
        }
        //4 更新缓存（频道）
        updateArticleCache(apArticle, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + apArticle.getChannelId());
        //5 更新推荐列表的缓存
        updateArticleCache(apArticle, score,  ArticleConstants.HOT_ARTICLE_FIRST_PAGE+ ArticleConstants.DEFAULT_TAG);
    }

    /**
     * 更新文章缓存
     * @param apArticle  当前文章
     * @param score 分数
     * @param cacheKey
     */
    private void updateArticleCache(ApArticle apArticle, long score, String cacheKey) {
        boolean noHas = true;
        String hotArticleListJson = (String) redisTemplate.opsForValue().get(cacheKey);
        if (StringUtils.isNotBlank(hotArticleListJson)) {
            List<HotArticleVo> hotArticleList = JSONArray.parseArray(hotArticleListJson,HotArticleVo.class);
            //1 如果当前缓存中有当前文章，更新分值
            for (HotArticleVo hotArticleVo : hotArticleList) {
                if (hotArticleVo.getId().equals(apArticle.getId())) {
                    hotArticleVo.setScore(score);
                    noHas = false;
                    break;
                }
            }
            //2 缓存中没有当前文章
            if (noHas) {
                HotArticleVo hotArticle = new HotArticleVo();
                BeanUtils.copyProperties(apArticle, hotArticle);
                hotArticle.setScore(score);
                hotArticleList.add(hotArticle);
            }
            //3. 将热点文章集合 按得分降序排序  取前30条缓存至redis中
            hotArticleList = hotArticleList.stream()
                    .sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                    .limit(30)
                    .collect(Collectors.toList());
            redisTemplate.opsForValue().set(cacheKey, JSON.toJSONString(hotArticleList));
        }
    }
}
